#include "bzbtime/timeutils.h"

#include "bzbutil/platform.h"
#include "bzbstring/stringutils.h"


bzbtime::time::time(std::tm *right_now) {

	if (right_now) {
		year = right_now->tm_year + 1900;
		month = right_now->tm_mon + 1;
		day = right_now->tm_mday;
		hour = right_now->tm_hour;
		min = right_now->tm_min;
		sec = right_now->tm_sec;
	}
}


std::string bzbtime::time::to_string(const std::string &format) const {

	std::string output = format;

	bzbstring::replace(output, "YY", std::to_string(year));
	bzbstring::replace(output, "MM", std::to_string(month));
	bzbstring::replace(output, "DD", std::to_string(day));
	bzbstring::replace(output, "hh", std::to_string(hour));
	bzbstring::replace(output, "mm", std::to_string(min));
	bzbstring::replace(output, "ss", std::to_string(sec));

	return output;
}


bzbtime::time bzbtime::get_localtime() {

	const std::time_t time_now = std::time(nullptr);

#ifdef _COMPILER_MSVC

	std::tm now;
	localtime_s(&now, &time_now);
	return bzbtime::time(&now);

#endif

#ifdef WINDOWS

	return bzbtime::time(localtime(&time_now));

#elif defined(LINUX)

	std::tm now;
	localtime_r(&time_now, &now);
	return time(&now);

#endif

}
